package menulogic

import (
	"context"

	"go-zero-admin/apps/system/cmd/rpc/internal/svc"
	"go-zero-admin/apps/system/cmd/rpc/syspb"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetMenuTreeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetMenuTreeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMenuTreeLogic {
	return &GetMenuTreeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetMenuTreeLogic) GetMenuTree(in *syspb.GetMenuTreeReq) (*syspb.GetMenuTreeResp, error) {
	if len(in.GetList()) == 0 {
		return &syspb.GetMenuTreeResp{Tree: nil}, nil
	}

	// 处理数据
	var tree []*syspb.SysMenuTree
	for _, menu := range in.GetList() {
		if menu.Pid != in.GetPid() {
			continue
		}

		t := &syspb.SysMenuTree{
			Menu: menu,
		}

		child, _ := l.GetMenuTree(&syspb.GetMenuTreeReq{
			Pid:  menu.Id,
			List: in.GetList(),
		})
		t.Children = child.Tree

		tree = append(tree, t)
	}
	return &syspb.GetMenuTreeResp{Tree: tree}, nil
}
